Online-Academy
Look, Read, Understand, Apply

Custom Exception

Custom Exception

In Java, you can create your own custom exception classes by extending the built-in Exception class (for checked exceptions) or RuntimeException class (for unchecked exceptions).

Custom Exceptions are important because:
  • To represent application-specific errors
  • To provide meaningful messages and structured error handling
  • To make code cleaner and easier to debug
  •     class MyException extends Exception{
        MyException(){
            super();
        }
        MyException(String s){
            super(s);
        }
    }
    
    class MyException_demo{
        public static void checkNum(int x) throws MyException{
            if(x % 2 == 0)
                throw new MyException("Even not required!");
        }
        public static void main(String[] aar){
            
            int[] ids = {1,2,3,4,5,6};
            try{
                checkNum(21); //If even number is given Custom Exception will be thrown
                for(int x: ids){
                    if(x > 5) //if x is greater than 5 exception will be thrown
                        throw new MyException("Greater than 5");
                }
            }catch(MyException e){
                System.out.println(" Excep: "+e.getMessage());
            }
        }
    }